import { _decorator, AudioClip, AudioSource, Component, Node } from 'cc';
import { Loader } from '../tools/LoadManger';
import { ComSingleton } from '../tools/Singleton';
import { GameData } from '../system/GameData';
import { DataHelper } from '../system/DataHelper';
import { ConfigKey } from './AppControll';
const { ccclass, property } = _decorator;

@ccclass('SoundManager')
export class SoundManager extends ComSingleton<SoundManager> {
    @property(AudioSource)
    mBgmAudio: AudioSource = null;

    private mAudioSource: AudioSource = null;

    private mBlIsReady: boolean = false;


    protected onLoad(): void {
        SoundManager._Instance = this;
        this.mAudioSource = this.node.getComponent(AudioSource);
    }

    InitSound(back: () => void) {
        this.mAudioSource.loop = true;
        Loader.LoadSoundDir(back);
    }

    PlayBgm() {
        let path = "ui/bgm";
        Loader.LoadSound(path, (audio: AudioClip) => {
            this.mBgmAudio.clip = audio;
            if (!this.mBgmAudio.playing && GameData.playerData.musicSwitch) {
                this.mBgmAudio.volume = Number.parseFloat(DataHelper.GetConfigByKey(ConfigKey.bgmVolume).value);
                this.mBgmAudio.play();
            }
        })
    }

    PlayFindFaultBGM() {
        let path = "terrorBGM";
        Loader.LoadSound(path, (audio: AudioClip) => {
            this.mAudioSource.clip = audio;
            if (!this.mAudioSource.playing && GameData.playerData.musicSwitch) {
                this.mAudioSource.play();
            }
        })
    }

    PlayEffect(fileName: string, volume?: number) {
        Loader.LoadSound(fileName, (audio: AudioClip) => {
            if (GameData.playerData.effectSwitch) {
                if (volume != null) {
                    this.mAudioSource.playOneShot(audio, volume);
                } else {
                    this.mAudioSource.playOneShot(audio)
                }

            }
        })
    }

    StopEffect() {
        if (!this.mAudioSource) return;
        this.mAudioSource.stop();
    }

    StopBgm() {
        if (!this.mBgmAudio) return;
        this.mBgmAudio.stop();
    }
}


